package com.jweb.phone.suport.config;

import java.util.HashMap;
import java.util.Map;

import com.jweb.config.JWebConfig;
import com.jweb.config.Plugins;
import com.jweb.core.JWebFilter;
import com.jweb.log.Logger;
import com.jweb.plugin.c3p0.C3p0Plugin;
import com.jweb.plugin.dynamicdatasource.DataSourceHolder;
import com.jweb.plugin.dynamicdatasource.DynamicDataSource;
import com.jweb.plugin.jdbc.JdbcTemplate;
//import com.jweb.plugin.jredis.RedisPlugin;
import com.jweb.plugin.mybatis.MybatisPlugin;

//import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;

/**
 * 系统配置
 * @author Yuanqy
 *
 */
public class JConfig extends JWebConfig {
	private Logger log = Logger.getLogger(getClass());

	@Override
	public void configConstant(Map<String, String> constants) {
		// 系统常量配置区，可覆盖默认配置
		// constants.put(key, value);
	}

	@Override
	public void configPlugin(Plugins plugins) throws Exception {
		log.info("加载插件...");
		// ==C3p0 连接池 可读写分离
		C3p0Plugin c3p0Plugin_write = new C3p0Plugin(getConstant("jdbc.url"), getConstant("jdbc.username"), getConstant("jdbc.password"));
		c3p0Plugin_write.start();
		plugins.add(c3p0Plugin_write);

		// ==DynamicDataSource可以配置N个数据源，在数据库操作中可以做到动态切换，
		// ==但在事物中，一旦指定，无法切换[无效]。
		Map<String, DataSource> targetDataSources = new HashMap<String, DataSource>();
//		targetDataSources.put("read", c3p0Plugin_read.getDataSource());
		targetDataSources.put("write", c3p0Plugin_write.getDataSource());
		DynamicDataSource dds = new DynamicDataSource(targetDataSources);
		dds.setLenientFallback(true);// 默认false
		// == jdbcTemplete 测试多数据源
		{
			JWebFilter.setJdbctemplate(new JdbcTemplate(dds));
			JdbcTemplate jt = JWebFilter.getJdbctemplate();
//			DataSourceHolder.setDbType("read");
//			System.err.println("当前数据库::" + jt.query("SELECT VERSION()", null).toString());
			DataSourceHolder.setDbType("write");
			System.err.println("当前数据库write::" + jt.query("SELECT VERSION()", null).toString());
			System.err.println(getConstant("jdbc.url"));//删掉这行
		}
		// ==Mybatis
//		MybatisPlugin mybatisPlugin_read = new MybatisPlugin(dds, "com.jweb.phone.web.dao", "sql.mapper");
//		mybatisPlugin_read.start();
//		plugins.add(mybatisPlugin_read);

		// ==Jedis
		// RedisPlugin redisPlugin = new RedisPlugin("123.57.43.202", 6379,
		// "redis_1", "foobared");
		// redisPlugin.start();
		// plugins.add(redisPlugin);
		// ==Dubbo-zookeeper
		// long times = System.currentTimeMillis();
		// log.info("SpringContext加载ing");
		// new ClassPathXmlApplicationContext(new String[] {
		// "application-dubbo-server.xml" }).start();
		// log.info("SpringContext加载完毕\t\t\t[{}]", new Object[] {
		// System.currentTimeMillis() - times });
	}

	public static void main(String[] args) {
		// new JettyServer("src/main/webapp", 8080, "/", 5).start();
	}
}
